package com.cy.store.service.impl;

import com.cy.store.entity.CartVO;
import com.cy.store.entity.OrderItem;
import com.cy.store.entity._Address;
import com.cy.store.entity._Order;
import com.cy.store.repository.OrderItemRepository;
import com.cy.store.repository.OrderRepository;
import com.cy.store.service.IAddressService;
import com.cy.store.service.ICartService;
import com.cy.store.service.IOrderService;
import com.cy.store.service.ex.InsertException;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private ICartService cartService;
    @Autowired
    private OrderItemRepository orderItemRepository;


    @Override
    public _Order create(Integer aid, Integer[] cids, Integer uid, String username) {
        //根据cid查询勾选的购物车内数据
        List<CartVO> carts = cartService.getVOByCids(uid,cids);

        //计算商品总价
        long totalPrice = 0;
        for (CartVO cart: carts)
            totalPrice += cart.getRealPrice() * cart.getNum();

        //创建订单，并补全数据
        _Order order = new _Order();
        order.setUid(uid);
        _Address address = addressService.getByAid(aid, uid);
        order.setRecvName(address.getName());
        order.setRecvPhone(address.getPhone());
        order.setRecvProvince(address.getProvinceName());
        order.setRecvCity(address.getCityName());
        order.setRecvArea(address.getAreaName());
        order.setRecvAddress(address.getAddress());
        order.setTotalPrice(totalPrice);
        order.setStatus(0);
        order.setOrderTime(new Date());
        order.setCreatedUser(username);
        order.setCreatedTime(new Date());
        order.setModifiedUser(username);
        order.setModifiedTime(new Date());

        //插入订单数据
        if(orderRepository.save(order)==null) throw new InsertException("插入订单失败，请重试");

        //遍历carts，循环插入订单商品数据
        for(CartVO cart: carts){
            //创建订单商品数据
            OrderItem item = new OrderItem();
            //补全数据
            item.setOid(order.getOid());
            item.setPid(cart.getPid());
            item.setTitle(cart.getTitle());
            item.setImage(cart.getImage());
            item.setPrice(cart.getRealPrice());
            item.setNum(cart.getNum());
            item.setCreatedUser(username);
            item.setCreatedTime(new Date());
            item.setModifiedUser(username);
            item.setModifiedTime(new Date());
            //插入数据
            if(orderItemRepository.save(item)==null) throw new InsertException("插入商品数据失败，请重试");
        }

        return order;
    }
}
